// ==UserScript==
// @name        random searx
// @description gives a random searx instance
// @version     1
// @run-at      document-start
// @grant       none
// @namespace   ?q=test
// ==/UserScript==

const domainCheck = /(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]/g;
const url = 'https://2/data/instances.json';

let currentURL = window.location.toString();
let answer = [];

// Fallback instance is set as search.fshm.in if the fetch query fails for some reason
let randomInstance = 'search.fshm.in';


if(currentURL.match(domainCheck)) {
	console.log("it's a domain");
  console.log(currentURL);
}

else {
  fetch(url)
  .then(response => response.json())
  .then(response => {
  searx_data = response.instances;
  for (let key in searx_data)
      if (searx_data[key]['http']['grade']=='A+')
          if ('tls' in searx_data[key])
              if (searx_data[key]['tls']['grade']=='A+')
                  if ('html' in searx_data[key]) {
                    temp = searx_data[key]['html']['grade'];
                    if (temp=='V' || temp=='C')
                        answer.push(key);
                  }
  randomInstance = answer[Math.floor(Math.random() * answer.length)];
  console.log("instance search done");
  console.log(randomInstance)
	})
  const randomInstanceNoProtocol = randomInstance.replace(/^https?\:\/\//i, "");
  window.location = currentURL.replace(currentURL, randomInstanceNoProtocol+'?q='+currentURL);
  
}

// if (currentUrl.indexOf('blog.sahilister.in') !== - 1) {
//   const randomInstanceNoProtocol = randomInstance.replace(/^https?\:\/\//i, "");
//   window.location = currentURL.replace('blog.sahilister.in/', randomInstanceNoProtocol+'?q=');
